package com.dk.controller;

import com.dk.pojo.TAuthor;
import com.dk.service.AuthorService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("authorController")
public class AuthorController {

    @Autowired
    private AuthorService authorService;

    //跳转作者表信息
    @RequestMapping("tolist")
    public String toList(){
        return "author/list";
    }

    @RequestMapping("getInfo")
    @ResponseBody
    public Map<String, Object> getServerUserInfo(@RequestParam(defaultValue="1") Integer pageNum, @RequestParam(defaultValue="5") Integer pageSize) {
        PageInfo<TAuthor> page = null;
        Map<String, Object> map = null;
        try {
            page = authorService.getInfo(pageNum, pageSize);
            map = new HashMap<>();
            map.put("total", page.getTotal());
            map.put("rows", page.getList());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    //跳转增加页面
    @RequestMapping("toAdd")
    public String toAdd() {
        return "author/add";
    }

    //增加数据
    @RequestMapping("add")
    @ResponseBody
    public boolean addChanel(TAuthor author) {
        int i = 0;
        try {
            i = authorService.add(author);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i > 0;
    }
    //回显
    @RequestMapping("toUpdate/{authorId}")
    public String toUpdate(@PathVariable("authorId") Integer authorId, Model model) {
        TAuthor c = null;
        List<TAuthor> list = null;
        try {
            list = authorService.getInfoByChannnel();
            model.addAttribute("list", list);
            c = authorService.toUpdate(authorId);
            model.addAttribute("c", c);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "author/update";
    }

    //修改
    @RequestMapping("update")
    @ResponseBody
    public boolean updateChannel(TAuthor author) {
        int i = 0;
        try {
            i = authorService.updateChannel(author);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i > 0;
    }
    //单条删除
    @RequestMapping("deleteInfoById/{authorId}")
    @ResponseBody
    public boolean deleteInfoById(@PathVariable("authorId") Integer authorId) {
        int i = 0;
        try {
            i = authorService.deleteInfoById(authorId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i > 0;
    }
}
